package org.bootstrap.start;

import cn.hutool.core.lang.Console;
import com.mongodb.client.MongoCollection;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Objects;

/**
 * 初始化数据表
 */
@Component
@Configuration
@PropertySource(value = "classpath:application-dev.yml")
public class DataBaseInstaller {
    @Value(value = "${spring.datasource.driver-class-name}")
    private String path_driver;

    @Value(value = "${spring.datasource.url}")
    private String jdbc_url;

    @Value(value = "${spring.datasource.username}")
    private String username;

    @Value(value = "${spring.datasource.password}")
    private String password;

    private static final ArrayList<String> sqlArray = new ArrayList<>();


    // 启动初始化表
    @PostConstruct
    public void init_table() {
        Console.log("初始化数据库表");
        try (Connection conn = DriverManager.getConnection(jdbc_url, username, password)) {
            Class.forName(path_driver); // 加载驱动
            String database = "CREATE DATABASE pq_sys"; // Pq_Sys 数据库名字 创建数据库
            PreparedStatement state_database = conn.prepareStatement(database);
            state_database.execute();
            PreparedStatement usePqSys = conn.prepareStatement("USE pq_sys");
            usePqSys.execute(); // 选中数据库
            usePqSys.close();
        } catch (SQLException e) {
            String string = e.getMessage();
            Console.error(string);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("未找到JDBC驱动");
        } catch (Exception e) {
            Console.log(e.getMessage());
        }
    }
}
